﻿using DoNet.ApiHttpClient.Entitys;
using DoNet.Common.Helpers;
using Microsoft.Extensions.DependencyInjection;

namespace DoNet.ApiHttpClient.WechatApi
{
    /// <summary>
    /// 微信API HttpClient 请求服务
    /// </summary>
    public static class WechatApiSetup
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        public static void AddHttpClientWechatApi(this IServiceCollection services)
        {
            string httpClientName = "WechatApiClient";
            var wechatApiClient = ConfigHelper.GetSection<HttpClientApi>("ApiHttpClients:" + httpClientName);
            if (wechatApiClient != null)
            {
                var sslProtocols = SslHelper.GetSsl(wechatApiClient.SslProtocols);
                if (wechatApiClient.Domains.Count > 0)
                {
                    //循环API域名
                    foreach (var api in wechatApiClient.Domains)
                    {
                        var httpClientBuilder = services.AddHttpClient($"{httpClientName}_{api.index}", client =>
                        {
                            client.BaseAddress = new Uri(DomainHelper.GetDomainName(api.domain, "", wechatApiClient.IsUseHttps));
                        });
                        httpClientBuilder.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
                        {
                            SslProtocols = sslProtocols
                        });
                    }
                }
            }

            // 注册服务
            services.AddSingleton<WechatApiService>(); 
        }
    }
}
